package com.mcr.graduateprogram.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.fastjson.JSONObject;
import com.mcr.graduateprogram.bean.KeysExcel;
import com.mcr.graduateprogram.service.IPhotoUpload;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class PhotoUploadImpl implements IPhotoUpload {
    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value(("${qiniu.url}"))
    private String url;
    @Override
    public String photoUpload(MultipartFile photo, String path) {
        Auth auth=Auth.create(accessKey,secretKey);
        String uploadToken = auth.uploadToken(bucket);
        Configuration cfg = new Configuration(Region.autoRegion());
        UploadManager uploadManager=new UploadManager(cfg);
        String key=path+ UUID.randomUUID().toString().replace("-","");
        String resp=null;
        try{
            Response response=uploadManager.put(photo.getInputStream(),key,uploadToken,null,null);
            resp=url+ JSONObject.parseObject(response.bodyString()).get("key");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            return resp;
        }
    }

    @Override
    public void downloadExcel(Long specificationId, Integer number, HttpServletResponse response) {
        List<KeysExcel> keysExcelList=new ArrayList<>();
        keysExcelList.add(new KeysExcel(specificationId,null));
        keysExcelList.add(new KeysExcel(Long.valueOf(number),null));
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            EasyExcel.write(response.getOutputStream(),KeysExcel.class)
                        .registerConverter(new LongStringConverter())
                        .sheet("激活码进货模板")
                        .doWrite(keysExcelList);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
